package com.xiaofu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaofu.enums.BizCodeEnum;
import com.xiaofu.enums.SendCodeEnum;
import com.xiaofu.interceptor.LoginInterceptor;
import com.xiaofu.mapper.UserMapper;
import com.xiaofu.model.LoginUser;
import com.xiaofu.model.UserDO;
import com.xiaofu.request.UserLoginRequest;
import com.xiaofu.request.UserRegisterRequest;
import com.xiaofu.service.NotifyService;
import com.xiaofu.service.UserService;
import com.xiaofu.utils.CommonUtil;
import com.xiaofu.utils.JWTUtil;
import com.xiaofu.utils.JsonData;
import com.xiaofu.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 邮箱验证码验证
     * 密码加密（TODO）
     * 账号唯一性检查(TODO)
     * 插入数据库
     * 新注册用户福利发放(TODO)
     * @param registerRequest
     * @return
     */
    @Override
    public JsonData register(UserRegisterRequest registerRequest) {
        boolean checkCode = false;
        // 校验验证码
        if (StringUtils.isNotBlank(registerRequest.getCode())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, registerRequest.getAccount(), registerRequest.getCode());
        }

        if(!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerRequest,userDO);
        userDO.setSlogan("人生需要动态规划,学习需要动态算法");
        userDO.setCreateTime(new Date());
        userDO.setMail(registerRequest.getAccount());
        // 设置密码 TODO
//        userDO.setPwd(registerRequest.getPwd());
        // 生成秘钥 盐
        userDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));

        // 密码+ 盐处理
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(), userDO.getSecret());

        userDO.setPwd(cryptPwd);

        // 账号唯一性检查 TODO
        if (checkUnique(userDO.getMail())) {
            int rows = userMapper.insert(userDO);

            log.info("rows: {},注册成功: {}",rows,userDO);

            // 新用户注册成功, 初始化信息,发放福利等  TODO
            userRegisterInitTask(userDO);

            return JsonData.buildSuccess();
        }

        return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
    }

    /**
     * 根据mail去找有没有记录
     * 有的话,则用秘钥+用户传递的明文密码,进行加密,在和数据库密文进行匹配
     * @param request
     * @return
     */
    @Override
    public JsonData login(UserLoginRequest request) {
        List<UserDO> userDOS = userMapper.selectList(new LambdaQueryWrapper<UserDO>().eq(UserDO::getMail, request.getMail()));
        if (userDOS != null && userDOS.size() == 1) {
            // 已经注册
            UserDO userDO = userDOS.get(0);
            String cryptPwd = Md5Crypt.md5Crypt(request.getPwd().getBytes(), userDO.getSecret());
            if (cryptPwd.equals(userDO.getPwd())) {
                // 登录成功,生成token
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO,loginUser);
                String token = JWTUtil.generateJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        } else {
            // 未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public UserVO findUserDetail() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        UserDO userDO = userMapper.selectById(loginUser.getId());
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDO,userVO);
        return userVO;
    }

    /**
     * 校验用户账号唯一性
     * @param mail
     * @return
     */
    private boolean checkUnique(String mail) {
        List<UserDO> userDOS = userMapper.selectList(new LambdaQueryWrapper<UserDO>().eq(UserDO::getMail, mail));
        return userDOS.isEmpty();
    }

    /**
     * 用户注册, 初始化福利信息 TODO
     * @param userDO
     */
    private void userRegisterInitTask(UserDO userDO) {

    }

}
